package com.luck.easyfoodbatch.getui;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.gson.Gson;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.MainActivity;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.db.MessageDB;
import com.luck.easyfoodbatch.entity.Message;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.ui.MessageActivity;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.Tools;

import java.util.List;

public class PushDemoReceiver extends BroadcastReceiver {

    /**
     * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView ==
     * null)
     */
    private final String TAG = "PushDemoReceiver";
    private Gson gson;
    private MessageDB messageDB;

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        gson = new Gson();
        messageDB = new MessageDB(context);
        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_MSG_DATA:
                byte[] payload = bundle.getByteArray("payload");
                String taskid = bundle.getString("taskid");
                String messageid = bundle.getString("messageid");

                // smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
                boolean result = PushManager.getInstance().sendFeedbackMessage(
                        context, taskid, messageid, 90001);
                System.out.println("第三方回执接口调用" + (result ? "成功" : "失败"));
                if (payload != null) {
                    String data = new String(payload);
                    if (!Tools.isNull(data)) {
                        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
                        if (user != null) {
                            Message message = gson.fromJson(data, Message.class);
                            messageDB.saveMessage(message);
                            sendNotification(context, message);
                        }
                    }
                }
                break;

            case PushConsts.GET_CLIENTID:
                // 获取ClientID(CID)
                break;

            case PushConsts.THIRDPART_FEEDBACK:

                break;

        }
    }


    /**
     * 系统通知
     *
     * @param context
     * @param item
     */
    public void sendNotification(Context context, Message message) {
        long when = System.currentTimeMillis(); // 通知产生的时间，会在通知信息里显示
        String content = message.getContent();
        String title = message.getTitle();
        int type = message.getType();
        String text = "";
        if (Tools.isNull(content)) {
            text = "你有一条新的系统消息！";
        } else {
            text = content;
        }

        Intent resultIntent = new Intent();
        Bundle bundle = new Bundle();
        if (!isApplicationBroughtToBackground(context)) {
            bundle.putInt("currIndex", 1);
            if (message.getType() == 1) {
                // 系统消息
                resultIntent.setClass(context, MessageActivity.class);
            } else if (message.getType() == 2) {
                // 订单消息
                resultIntent.setClass(context, MessageActivity.class);
            }
            resultIntent.putExtras(bundle);
        } else {
            resultIntent.setClass(context, MainActivity.class);
            bundle.putInt("type", Tools.formatInt(type));
            resultIntent.putExtras(bundle);
        }
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                context).setSmallIcon(R.mipmap.ic_launcher).setWhen(when).setDefaults(Notification.DEFAULT_SOUND)
                .setContentTitle(title)
                .setContentText(text);
        mBuilder.setTicker(text);//第一次提示消息的时候显示在通知栏上
        mBuilder.setAutoCancel(true);//自己维护通知的消失

        //封装一个Intent
        PendingIntent resultPendingIntent = PendingIntent.getActivity(
                context, 0, resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        // 设置通知主题的意图
        mBuilder.setContentIntent(resultPendingIntent);
        //获取通知管理器对象
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(0, mBuilder.build());
    }


    /**
     * 需要权限:android.permission.GET_TASKS
     *
     * @param context
     * @return
     */
    public boolean isApplicationBroughtToBackground(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (tasks != null && !tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }
}
